package hotLeetcode;

import java.util.*;

public class H347Leetcode {

    public static int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] ans = new int[k];


        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);

        }


        List<Integer> list = map.entrySet().stream().sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
                .limit(k)
                .map(Map.Entry::getKey)
                .toList();


        for (int i = 0; i < k; i++) {
            ans[i] = list.get(i);
        }

        return ans;


    }



    public static int[] topKFrequent1(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] ans = new int[k];


        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);

        }


        PriorityQueue<Integer> heap = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return map.get(o1)-map.get(o2);
            }
        });

        for (Integer key : map.keySet()) {
            heap.add(key);
            if (heap.size() > k) {
                heap.poll();
            }
        }

        for (int i = k - 1; i >= 0; i--) {
            ans[i] = heap.poll();

        }


        return ans;


    }




    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        int k = 2;

        System.out.println(Arrays.toString(H347Leetcode.topKFrequent1(nums, k)));

    }

}
